﻿using System;
using System.Globalization;
using System.Windows.Data;

namespace SuperQuery.Converters
{
    /// <summary>
    /// Invert a boolean value so true is converted to false and vice versa
    /// </summary>
    public class InverseBoolConverter : IValueConverter
    {
        /// <summary>
        /// Converts true to false and false to true 
        /// </summary>
        /// <returns>
        /// A converted value. If the method returns null, the valid null value is used.
        /// </returns>
        /// <param name="value">The value produced by the binding source.</param>
        /// <param name="targetType">The type of the binding target property.</param>
        /// <param name="parameter">The converter parameter to use.</param>
        /// <param name="culture">The culture to use in the converter.</param>
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return InvertValue(value);
        }

        /// <summary>
        /// Converts false back into true and true back into false 
        /// </summary>
        /// <returns>
        /// A converted value. If the method returns null, the valid null value is used.
        /// </returns>
        /// <param name="value">The value that is produced by the binding target.</param>
        /// <param name="targetType">The type to convert to.</param>
        /// <param name="parameter">The converter parameter to use.</param>
        /// <param name="culture">The culture to use in the converter.</param>
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return InvertValue(value);
        }

        /// <summary>
        /// If the supplied value is not null and is boolean then invert it
        /// </summary>
        /// <param name="value">An object that contains a boolean value</param>
        /// <returns>If value is "false" then return "true" and vice versa</returns>
        private bool InvertValue(object value)
        {
            bool result = false;

            if ((value != null) && (value is bool))
            {
                result = !((bool)value);
            }

            return result;
        }
    }
}
